function file_list = dirlist(path_name, descend_flag);

% DIRLIST - obtain a listing of file names
%
%    LIST = DIRLIST(PATH) obtains a list of file names contained
%    within the directory specified by PATH.  LIST is a structure
%    containing the path, file name and file extension for each
%    file.
%
%    LIST = DIRLIST(PATH, 'descend') obtains file names contained
%    within the directory specified by PATH and all subdirectories
%    contained within PATH.  This is performed by making recursive
%    calls to DIRLIST.  The directories root ('..') and current
%    ('.') are not accessed to avoid infinite loops.

% S.C. Molitor (smolitor@med.unc.edu)
% Date: August 24, 1999

% initialize output to prevent MATLAB errors

file_list = [];

% check command line arguments

if (nargin < 1) | (nargin > 2)
   msgbox('Invalid number of function arguments', 'DIRLIST Error', 'warn');
   return
elseif (~ischar(path_name))
   msgbox('Function arguments must be of type CHAR', 'DIRLIST Error', 'warn');
   return
elseif (exist(path_name) ~= 7)
   msgbox([path_name ' is not a valid directory'], 'DIRLIST Error', 'warn');
   return
elseif (nargin == 1)
   descend_flag = 'nodescend';
elseif (~ischar(descend_flag))
   msgbox('Function arguments must be of type CHAR', 'DIRLIST Error', 'warn');
   return
end

% obtain directory contents

dir_struct = dir(path_name);
for i = 1 : length(dir_struct)
   
   % copy path, file name & file extension to output
   % only obtain file extension where appropriate
   
   if (dir_struct(i).isdir == 0)
      file_name = dir_struct(i).name;
      dot_pos = findstr(file_name, '.');
      if (isempty(dot_pos))
         file_ext = '';
      elseif ((dot_pos(end) <= 1) | (dot_pos(end) >= length(file_name)))
         file_ext = '';
      else
         file_ext = file_name(dot_pos(end) : end);
         file_name = file_name(1 : dot_pos(end) - 1);
      end
      file_list(end + 1).path = path_name;
      file_list(end).name = file_name;
      file_list(end).ext = file_ext;
      
      % only descend subdirectories if specified
      % do not descend '.' and '..' directories
      % recursively call DIRLIST to obtain subdirectory contents
      
   elseif ((dir_struct(i).isdir == 1) & (strcmp(descend_flag, 'descend')))
      subdir_name = [dir_struct(i).name '\'];
      if (~strcmp(subdir_name, '.\') & ~strcmp(subdir_name, '..\'))
         add_list = dirlist([path_name subdir_name], descend_flag);
         if (isempty(file_list))
            file_list = add_list;
         else
            file_list(end + 1 : end + length(add_list)) = add_list;
         end
      end
   end
end
return
